package com.java110.mall.chain.partner.adapter.hibo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.file.FileRelDto;
import com.java110.dto.partnerAdapt.PartnerGoodsDto;
import com.java110.dto.partnerAdapt.PartnerPoolDto;
import com.java110.dto.partnerAdapt.PartnerPoolValueDto;
import com.java110.intf.chain.IPartnerLogV1InnerServiceSMO;
import com.java110.intf.chain.IPartnerPoolValueV1InnerServiceSMO;
import com.java110.intf.goods.IPartnerGoodsV1InnerServiceSMO;
import com.java110.intf.goods.IProductInnerServiceSMO;
import com.java110.intf.goods.IProductSpecValueInnerServiceSMO;
import com.java110.intf.system.IFileRelInnerServiceSMO;
import com.java110.mall.chain.partner.IPartnerAdapter;
import com.java110.mall.chain.partner.adapter.hibo.utils.HiBoConfig;
import com.java110.mall.chain.partner.adapter.hibo.utils.HiboService;
import com.java110.po.partnerAdapt.PartnerGoodsPo;
import com.java110.po.partnerAdapt.PartnerLogPo;
import com.java110.utils.cache.MappingCache;
import com.java110.utils.constant.MappingConstant;
import com.java110.utils.util.ListUtil;
import com.java110.utils.util.StringUtil;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("hiboosAdaptImpl")
public class HiboosAdaptImpl implements IPartnerAdapter {

    /**
     * 正式域名: https://openerp.hiboos.com
     * <p>
     * 测试域名: https://pre-openerp.hiboos.com
     */
    public static final String HIBOOS_URL = "https://pre-openerp.hiboos.com";

    @Autowired
    private IPartnerPoolValueV1InnerServiceSMO partnerPoolValueV1InnerServiceSMOImpl;

    @Autowired
    private IPartnerGoodsV1InnerServiceSMO partnerGoodsV1InnerServiceSMOImpl;

    @Autowired
    private IProductInnerServiceSMO productInnerServiceSMOImpl;

    @Autowired
    private IProductSpecValueInnerServiceSMO productSpecValueInnerServiceSMOImpl;

    @Autowired
    private IFileRelInnerServiceSMO fileRelInnerServiceSMOImpl;

    @Autowired
    private IPartnerLogV1InnerServiceSMO partnerLogV1InnerServiceSMOImpl;

    @Override
    public ResultVo syncGoods(String ppId, String shopId) {

        String url = HIBOOS_URL + "/product/erp/syncVenderProduct";

        HiBoConfig hiBoConfig = getHiBoConfig(ppId, shopId);

        JSONArray bodys = new JSONArray();

        PartnerGoodsDto partnerGoodsDto = new PartnerGoodsDto();
        partnerGoodsDto.setState(PartnerGoodsDto.STATE_WAIT);
        partnerGoodsDto.setPpId(ppId);
        partnerGoodsDto.setShopId(shopId);
        List<PartnerGoodsDto> partnerGoodsDtos = partnerGoodsV1InnerServiceSMOImpl.queryPartnerGoodss(partnerGoodsDto);

        if (ListUtil.isNull(partnerGoodsDtos)) {
            throw new IllegalArgumentException("同步商品不存在");
        }

        JSONObject body = null;

        /**
         * {
         *         "goodsId": "001388",
         *         "outSkuId": "001388",
         *         "skuName": "250ml蒙牛纯牛奶",
         *         "unit": "包",
         *         "skuType": "1",
         *         "weight": 250,
         *         "upc": "6923644223458",
         *         "venderCategoryCodeLevel3": "530301",
         *         "venderCategoryNameLevel3": "保久乳",
         *         "spec": "250ml"
         *         }
         */
        for (PartnerGoodsDto tmpPartnerGoodsDto : partnerGoodsDtos) {
            body = new JSONObject();
            body.put("goodsId", tmpPartnerGoodsDto.getValueId());
            body.put("outSkuId", tmpPartnerGoodsDto.getValueId());
            body.put("skuName", tmpPartnerGoodsDto.getProdName());
            body.put("skuImg", getSkuImg(tmpPartnerGoodsDto));
            body.put("unit", tmpPartnerGoodsDto.getUnitName());
            body.put("skuType", "1");
            // body.put("weight", "");
            body.put("upc", tmpPartnerGoodsDto.getBarCode());
            body.put("venderCategoryCodeLevel3", tmpPartnerGoodsDto.getCategoryId());
            body.put("venderCategoryNameLevel3", tmpPartnerGoodsDto.getCategoryName());
            body.put("spec", tmpPartnerGoodsDto.getSpecName());
            body.put("productDesc", tmpPartnerGoodsDto.getProductDesc());
            bodys.add(body);
        }
        String result = "";
        String state = "10002";
        try {
            result = HiboService.call(url, hiBoConfig.getAppId(), bodys.toJSONString(), hiBoConfig.getSecure(), String.class);

            JSONObject paramOut = JSONObject.parseObject(result);
            if (paramOut.getIntValue("code") == 0) {
                PartnerGoodsPo partnerGoodsPo = new PartnerGoodsPo();
                partnerGoodsPo.setNewState(PartnerGoodsDto.STATE_Y);
                partnerGoodsPo.setState(PartnerGoodsDto.STATE_WAIT);
                partnerGoodsPo.setRemark(paramOut.getString("msg"));
                partnerGoodsPo.setPpId(ppId);
                partnerGoodsV1InnerServiceSMOImpl.updatePartnerGoods(partnerGoodsPo);
                return new ResultVo(ResultVo.CODE_OK, ResultVo.MSG_OK);
            }
            state = "10003";
            JSONArray resultDatas = paramOut.getJSONArray("result");

            JSONObject resultData = null;
            for (int rIndex = 0; rIndex < resultDatas.size(); rIndex++) {
                resultData = resultDatas.getJSONObject(rIndex);
                PartnerGoodsPo partnerGoodsPo = new PartnerGoodsPo();
                partnerGoodsPo.setNewState(PartnerGoodsDto.STATE_N);
                partnerGoodsPo.setState(PartnerGoodsDto.STATE_WAIT);
                partnerGoodsPo.setRemark(resultData.getString("msg"));
                partnerGoodsPo.setPpId(ppId);
                partnerGoodsPo.setValueId(resultData.getString("goodsId"));
                partnerGoodsV1InnerServiceSMOImpl.updatePartnerGoods(partnerGoodsPo);
            }
            return new ResultVo(ResultVo.CODE_ERROR, paramOut.getString("msg"));
        } finally {
            savePartnerLog("同步商品", bodys.toJSONString(), result, state, ppId, shopId);
        }


    }

    private void savePartnerLog(String action, String reqJson, String resJson, String state, String ppId, String shopId) {

        PartnerLogPo partnerLogPo = new PartnerLogPo();
        partnerLogPo.setPersonName("-");
        partnerLogPo.setResParam(resJson);
        partnerLogPo.setLogId(GenerateCodeFactory.getGeneratorId("11"));
        partnerLogPo.setPersonId("-1");
        partnerLogPo.setShopId(shopId);
        partnerLogPo.setReqParam(reqJson);
        partnerLogPo.setState(state);
        partnerLogPo.setLogAction(action);
        partnerLogPo.setPpId(ppId);
        partnerLogV1InnerServiceSMOImpl.savePartnerLog(partnerLogPo);

    }

    private String getSkuImg(PartnerGoodsDto tmpPartnerGoodsDto) {

        FileRelDto fileRelDto = new FileRelDto();
        fileRelDto.setObjId(tmpPartnerGoodsDto.getProductId());
        List<FileRelDto> fileRelDtos = fileRelInnerServiceSMOImpl.queryFileRels(fileRelDto);

        String imgUrl = MappingCache.getValue(MappingConstant.FILE_DOMAIN, "IMG_PATH");
        imgUrl += (!StringUtil.isEmpty(imgUrl) && imgUrl.endsWith("/") ? "" : "/");
        String imgs = "";
        String url = "";
        for (FileRelDto tmpFileRelDto : fileRelDtos) {

            //url = "/callComponent/download/getFile/file?fileId=" + tmpFileRelDto.getFileRealName() + "&communityId=-1"
            if (!tmpFileRelDto.getFileRealName().startsWith("http")) {
                url = imgUrl + tmpFileRelDto.getFileRealName();
            } else {
                url = tmpFileRelDto.getFileRealName();
            }
            imgs += url + ",";
        }
        return imgs;

    }

    @Override
    public ResultVo syncDeleteGoods(PartnerPoolDto partnerPoolDto, PartnerGoodsDto partnerGoodsDto) {
        HiBoConfig hiBoConfig = getHiBoConfig(partnerPoolDto.getPpId(), partnerPoolDto.getShopId());

        return new ResultVo(ResultVo.CODE_OK, ResultVo.MSG_OK);
    }

    @Override
    public ResultVo syncGoodsStock(PartnerPoolDto partnerPoolDto) {

        String url = HIBOOS_URL + "/stock/offline/batchSave";

        HiBoConfig hiBoConfig = getHiBoConfig(partnerPoolDto.getPpId(), partnerPoolDto.getShopId());

        JSONObject body = new JSONObject();

        body.put("outStationNo", hiBoConfig.getHiboShopId());

        JSONArray stocks = new JSONArray();


        PartnerGoodsDto partnerGoodsDto = new PartnerGoodsDto();
        partnerGoodsDto.setPpId(partnerPoolDto.getPpId());
        partnerGoodsDto.setShopId(partnerPoolDto.getShopId());
        List<PartnerGoodsDto> partnerGoodsDtos = partnerGoodsV1InnerServiceSMOImpl.queryPartnerGoodss(partnerGoodsDto);

        if (ListUtil.isNull(partnerGoodsDtos)) {
            throw new IllegalArgumentException("同步商品不存在");
        }

        JSONObject stock = null;

        for (PartnerGoodsDto tmpPartnerGoodsDto : partnerGoodsDtos) {
            stock = new JSONObject();
            stock.put("goodsId", tmpPartnerGoodsDto.getValueId());
            stock.put("outSkuId", tmpPartnerGoodsDto.getValueId());

            stock.put("stock", tmpPartnerGoodsDto.getStock());
            stocks.add(stock);
        }


        body.put("stocks", stocks);
        String result = "";
        String state = "10002";
        try {

            result = HiboService.call(url, hiBoConfig.getAppId(), body.toJSONString(), hiBoConfig.getSecure(), String.class);
            JSONObject paramOut = JSONObject.parseObject(result);

            if (paramOut.getIntValue("code") == 0) {
                return new ResultVo(ResultVo.CODE_OK, paramOut.getString("msg"));
            }

            state = "10003";
            JSONArray resultDatas = paramOut.getJSONArray("result");

            JSONObject resultData = null;
            String msg = "";
            for (int rIndex = 0; rIndex < resultDatas.size(); rIndex++) {
                resultData = resultDatas.getJSONObject(rIndex);
                msg += (resultData.getString("goodsId") + "-" + resultData.getString("msg") + ";");
            }

            return new ResultVo(ResultVo.CODE_ERROR, msg);
        } finally {
            savePartnerLog("同步库存", body.toJSONString(), result, state, partnerGoodsDtos.get(0).getPpId(), partnerGoodsDtos.get(0).getShopId());
        }
    }

    @Override
    public ResultVo syncGoodsPrice(PartnerPoolDto partnerPoolDto) {
        String url = HIBOOS_URL + "/price/offline/batchSave";

        HiBoConfig hiBoConfig = getHiBoConfig(partnerPoolDto.getPpId(), partnerPoolDto.getShopId());

        JSONObject body = new JSONObject();

        body.put("outStationNo", hiBoConfig.getHiboShopId());

        JSONArray prices = new JSONArray();


        PartnerGoodsDto partnerGoodsDto = new PartnerGoodsDto();
        partnerGoodsDto.setPpId(partnerPoolDto.getPpId());
        partnerGoodsDto.setShopId(partnerPoolDto.getShopId());
        List<PartnerGoodsDto> partnerGoodsDtos = partnerGoodsV1InnerServiceSMOImpl.queryPartnerGoodss(partnerGoodsDto);

        if (ListUtil.isNull(partnerGoodsDtos)) {
            throw new IllegalArgumentException("同步商品不存在");
        }

        JSONObject price = null;

        for (PartnerGoodsDto tmpPartnerGoodsDto : partnerGoodsDtos) {
            price = new JSONObject();
            price.put("goodsId", tmpPartnerGoodsDto.getValueId());
            price.put("outSkuId", tmpPartnerGoodsDto.getValueId());
            price.put("basicPrice", getHiboPrice(tmpPartnerGoodsDto.getPrice()));
            price.put("originalPrice", getHiboPrice(tmpPartnerGoodsDto.getOtPrice()));
            price.put("vipPrice", getHiboPrice(tmpPartnerGoodsDto.getVipPrice()));
            price.put("offlineSaleStatus", "1");
            price.put("productType", "2");
            prices.add(price);
        }


        body.put("prices", prices);
        String result = "";
        String state = "10002";
        try {
            result = HiboService.call(url, hiBoConfig.getAppId(), body.toJSONString(), hiBoConfig.getSecure(), String.class);
            JSONObject paramOut = JSONObject.parseObject(result);

            if (paramOut.getIntValue("code") == 0) {
                return new ResultVo(ResultVo.CODE_OK, paramOut.getString("msg"));
            }
            state = "10003";

            JSONArray resultDatas = paramOut.getJSONArray("result");

            JSONObject resultData = null;
            String msg = "";
            for (int rIndex = 0; rIndex < resultDatas.size(); rIndex++) {
                resultData = resultDatas.getJSONObject(rIndex);
                msg += (resultData.getString("outSkuId") + "-" + resultData.getString("msg") + ";");
            }

            return new ResultVo(ResultVo.CODE_ERROR, msg);
        } finally {
            savePartnerLog("同步价格", body.toJSONString(), result, state, partnerGoodsDtos.get(0).getPpId(), partnerGoodsDtos.get(0).getShopId());
        }
    }

    private long getHiboPrice(String price) {
        double priceDouble = Double.parseDouble(price) * 100;
        return  Math.round(priceDouble);
    }


    private HiBoConfig getHiBoConfig(String ppId, String shopId) {
        PartnerPoolValueDto partnerPoolValueDto = new PartnerPoolValueDto();
        partnerPoolValueDto.setShopId(shopId);
        partnerPoolValueDto.setPpId(ppId);
        List<PartnerPoolValueDto> partnerPoolValueDtos = partnerPoolValueV1InnerServiceSMOImpl.queryPartnerPoolValues(partnerPoolValueDto);

        if (ListUtil.isNull(partnerPoolValueDtos)) {
            throw new IllegalArgumentException("未配置海博信息");
        }

        String appId = PartnerPoolValueDto.getColumnValue(partnerPoolValueDtos, "AppId");
        String secret = PartnerPoolValueDto.getColumnValue(partnerPoolValueDtos, "secret");
        String hiboShopId = PartnerPoolValueDto.getColumnValue(partnerPoolValueDtos, "ShopId");

        return new HiBoConfig(appId, secret, hiboShopId);
    }
}
